"""免登录"""
import time, xlrd, xlwt
from pynput import keyboard
from pynput.keyboard import Key
from common.Base import open_browser, Base
from selenium.webdriver.common.by import By

"""通过获取cookies实现免登录"""


def get_token():
    """免登录第一步，获取COOKies"""
    driver = open_browser()
    driver.maximize_window()
    driver.get('https://music.163.com/')
    time.sleep(12)
    cookies = driver.get_cookies()

    workbook = xlwt.Workbook(encoding='utf-8')  # 创建一个workbook并设置编码
    worksheet = workbook.add_sheet('sheet1')  # 添加sheet
    worksheet.write(0, 0, 'name')  # 第一行第一列写入内容
    worksheet.write(0, 1, 'value')
    worksheet.write(0, 2, 'path')
    worksheet.write(0, 3, 'domain')
    worksheet.write(0, 4, 'secure')
    worksheet.write(0, 5, 'httpOnly')
    worksheet.write(0, 6, 'sameSite')
    for i in range(1, len(cookies) + 1):  # 1,2,3,4,5,6
        worksheet.write(i, 0, cookies[i - 1]['name'])
        worksheet.write(i, 1, cookies[i - 1]['value'])
        worksheet.write(i, 2, cookies[i - 1]['path'])
        worksheet.write(i, 3, cookies[i - 1]['domain'])
        worksheet.write(i, 4, cookies[i - 1]['secure'])
        worksheet.write(i, 5, cookies[i - 1]['httpOnly'])
        # worksheet.write(i, 6, cookies[i - 1]['sameSite'])
    workbook.save('../data/blogs_cookies.xls')  # 将以上内容保存到指定的文件中
    driver.quit()
    print('获取cook完成！')


class Login(Base):
    def no_login_token(self):
        """通过获取cookie实现免登录"""
        """免登录第二步，通过前面第一步获取到的cookice实现免登陆，前提是第一步已经执行过"""
        # get_token()  # """第一次执行时，需要执行这一行代码（获取cook），第二次既不需要重新登录获取cook了"""   """用if函数进行优化，判断表格内容来觉得是否需要调用"""
        self.open_url('https://music.163.com/')
        # self.open_url('http://www.baidu.com')
        workbook_open = xlrd.open_workbook('../data/blogs_cookies.xls')  # 使用xlrd创建一个工作薄对象
        sheet = workbook_open.sheet_by_name('sheet1')  # 根据工作表的名称创建表格对象
        cookie_list = []  # 创建一个空列表
        for row_num in range(1, sheet.nrows):
            cookie_dict = {}  # 创建一个空字典
            cookie_dict['name'] = sheet.cell_value(row_num, 0)
            cookie_dict['value'] = sheet.cell_value(row_num, 1)
            cookie_dict['path'] = sheet.cell_value(row_num, 2)
            cookie_dict['domain'] = sheet.cell_value(row_num, 3)
            cookie_dict['secure'] = bool(sheet.cell_value(row_num, 4))  # 注意因为这里的值是TRUE、FALSE是布尔类型,需要强转一下,否则会当成字符串
            cookie_dict['httpOnly'] = bool(sheet.cell_value(row_num, 5))
            # cookie_dict['sameSite'] = sheet.cell_value(row_num, 6)
            cookie_list.append(cookie_dict)  # 以字典形式装入列表,[{'name':'','value':'','path':''},{},{},{},{},{}]
        for cookie in cookie_list:
            self.driver.add_cookie(cookie)  # 再用for循环输出并add_cookie
        time.sleep(2)
        self.driver.refresh()  # 刷新浏览器即可免密登录
        time.sleep(5)
        print('免密登录成功！')

    """自动登录平台  适用于可以定位到登录框"""

    def login_element(self):
        '''
        使用举例:
        base=Base(open_browser())
        base.login_user()
        :return:
        '''
        self.open_url('http://mes.kopsoft.cn/sys/dict')  # 进入登录页面
        self._find_element((By.XPATH, '/html/body/div/div[1]/form/div[1]/div[1]/input')).send_keys('admin')  # 输入用户名
        self._find_element((By.XPATH, '/html/body/div/div[1]/form/div[1]/div[2]/input')).send_keys(
            'admin123456')  # 输入密码
        self._find_element((By.XPATH, '//*[@id="app"]/div/form/div[4]/div/button/span/span')).click()  # 点击登录

    """自动登录，适用于windows登录弹框 """

    def login_windows(self):
        self.open_url("http://10.0.0.83:3080/page/home")

        time.sleep(2)  # 加等待时间  避免按键操作过早报错
        obj = keyboard.Controller()

        #  press 按下按键 release 释放按键
        obj.press(Key.shift)  # 切换英文输入法
        obj.release(Key.shift)
        obj.type(f'sharewinfo\yanglin')  # 账号

        obj.press(Key.tab)  # 切换输入框
        obj.release(Key.tab)
        time.sleep(2)
        obj.type('1qaz@WSX@WSX')  # 密码

        obj.press(Key.enter)  # 登录
        obj.release(Key.enter)
        time.sleep(2)

if __name__ == '__main__':
    Login(open_browser()).no_login_token()
